TOP

SQL COUNT, AVG and SUM

SQL COUNT, AVG and SUM Description

The COUNT(), AVG(), and SUM() functions return the row count, average, and total of a numeric column, respectively.


The COUNT() function returns the number of rows that match the specified criteria.

COUNT() Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition

The AVG() function returns the average value of a numeric column.

AVG() Syntax

SELECT AVG(column_name)
FROM table_name
WHERE condition

The SUM() function returns the total sum of a numeric column.

SUM() Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition

Demonstration database

The following is a sample from the "Products" ("Products") table of the "Northwind" database:

ProductIDProductNameSupplierIDCategoryIDUnitPrice
1Chais1110 boxes x 20 bags18.00
2Chang1124 - 12 oz bottles19.00
3Aniseed Syrup1212 - 550 ml bottles10.00
4Chef Anton's Cajun Seasoning2248 - 6 oz jars22.00
5Chef Anton's Gumbo Mix2236 boxes21.35

COUNT() Example

The following SQL statement finds the number of products:

Run SQLSELECT COUNT(ProductID) 
FROM Products
NULL values ​​are ignored.

AVG() Example

The following SQL statement finds the average price of all products:

Run SQLSELECT AVG(Price) 
FROM Products
NULL values ​​are ignored.

Demonstration database

The following is a sample from the "OrderDetails" ("Order Details") table of the "Northwind" database:

OrderDetailIDOrderIDProductIDQuantity
1102481112
2102484210
310248725
410249149
5102495140

SUM() Example

The following SQL statement finds the sum of the "Quantity" ("Quantity") fields in the "OrderDetails" ("Order Details") table:

Run SQLSELECT SUM(Quantity) 
FROM OrderDetails
NULL values ​​are ignored.